// @Author miaoqing
// @Date 2024/02/27 15:42:00
// @Desc
package logic

import (
	"core/command"
	"core/common"
	"core/component/function"
	"core/component/logger"
	"core/network"
	"sync"
)

var (
	pcOnce       sync.Once
	pvpClientMgr *PvpClientMgr
)

type PvpClientMgr struct {
	clients *sync.Map
}

func pvpClientMgrGetMe() *PvpClientMgr {
	pcOnce.Do(func() {
		pvpClientMgr = &PvpClientMgr{
			clients: &sync.Map{},
		}
	})
	return pvpClientMgr
}

func (mgr *PvpClientMgr) discoveryPvpSrv() {
	resp := &common.GetAllServerInfoResp{}
	err := common.SendCenterHttpRequest(nil, resp, "GET", "/getAllPvpServer")
	if err != nil {
		return
	}
	mgr.clearInvalidPvpClient(resp.SInfos)
	for _, srv := range resp.SInfos {
		if _, ok := mgr.clients.Load(srv.ServerID); ok {
			continue
		}
		client := &PvpClient{
			tcpClient:  network.NewTcpClient(16*1024, 16*1024),
			serverID:   srv.ServerID,
			serverAddr: srv.Addr,
		}
		client.tcpClient.OnCloseCallBack = client.OnCloseCallBack
		mgr.addPvpClient(srv.ServerID, client)
	}
}

func (mgr *PvpClientMgr) addPvpClient(srvID string, client *PvpClient) {
	c, ok := mgr.clients.Load(srvID)
	if ok {
		gClient := c.(*PvpClient)
		logger.Warningf("网关连接已存在 ID:%v Addr:%v", gClient.serverID, gClient.serverAddr)
		return
	}
	//client.registerMsgs()
	mgr.clients.Store(srvID, client)
	logger.Infof("添加网关连接 srvID:%v Addr:%v", client.serverID, client.serverAddr)
}

func (mgr *PvpClientMgr) clearInvalidPvpClient(services []*common.ServerInfo) {
	mgr.clients.Range(func(k, v interface{}) bool {
		client, ok := v.(*PvpClient)
		if ok {
			find := false
			for _, svcEntry := range services {
				//info := function.GetPerformanceData(svcEntry.Service.Tags[0])
				//if client.ZoneId == info.Zid && client.serverID == svcEntry.Service.ID {
				if client.serverID == svcEntry.ServerID {
					find = true
				}
			}
			if !find {
				mgr.clients.Delete(client.serverID)
			}
		}
		return true
	})
}

func (mgr *PvpClientMgr) checkConnect() {
	mgr.clients.Range(func(key, value any) bool {
		client := value.(*PvpClient)
		client.checkConnect(client.serverAddr)
		return true
	})
}

func (mgr *PvpClientMgr) findAPvpClient() *PvpClient {
	value := function.RandSyncMap(mgr.clients)
	if value == nil {
		return nil
	}
	val, ok := mgr.clients.Load(value.(string))
	if !ok {
		return nil
	}
	return val.(*PvpClient)
}

func (mgr *PvpClientMgr) sendMsgToPvp(srvID string, cmd command.Command, msg interface{}) bool {
	client, ok := mgr.clients.Load(srvID)
	if ok && client != nil {
		pvp := client.(*PvpClient)
		return pvp.sendMsg(cmd, msg)
	} else {
		logger.Errorf("sendMsgToPvp %v %v", srvID, cmd)
		return false
	}
}

// 原始数据转发给home服务器的消息包
func (mgr *PvpClientMgr) forwardMsgToPvp(srvID string, userID uint64, data []byte) {
	client, ok := mgr.clients.Load(srvID)
	if ok && client != nil {
		msgSend := &command.PvpForwardPacket{
			Playerid: userID,
			//Pvpid:    homeID,
		}
		msgSend.Data = make([]byte, len(data))
		copy(msgSend.Data, data)
		pvp := client.(*PvpClient)
		pvp.sendMsg(command.Command_PvpForwardPacket_Server, msgSend)
	} else {
		logger.Warningf("unknow pvp server %v when formsg for user %v", srvID, userID)
		//logger.Warningf("unknow server %v %v", srvID, string(debug.Stack()))
	}
}

func (mgr *PvpClientMgr) centerClose() {
	mgr.clients = &sync.Map{}
}
